#include "av.h"
#include "include/clamav/clamav.h"
#include <stdio.h>

AntiVirus* AntiVirus::sm_inst = NULL;

AntiVirus::AntiVirus()
{
    engine = NULL;
}

AntiVirus::~AntiVirus()
{
    FreeMemory();
}

void AntiVirus::Init()
{
    AllocMemory();
}

int AntiVirus::AllocMemory()
{
    int ret;
    printf("Wait, initializing!\n");
    if ((ret = cl_init(CL_INIT_DEFAULT))) {
        printf("!Can't initialize libclamav: %s\n", cl_strerror(ret));
        return 2;
    }

    if (!(engine = cl_engine_new())) {
        printf("!Can't initialize antivirus engine\n");
        return 2;
    }


    //const char* dbdir = cl_retdbdir();
    const char* dbdir = "share";
    unsigned int signo = 0;
    unsigned int dboptions = 0;

    if ((ret = cl_load(dbdir, engine, &signo, dboptions))) {
        printf("!%s\n", cl_strerror(ret));

        cl_engine_free(engine);
        return 2;
    }


    if ((ret = cl_engine_compile(engine)) != 0) {
        printf("!Database initialization error: %s\n", cl_strerror(ret));

        cl_engine_free(engine);
        return 2;
    }


    printf("Init finished.\n");

    return 0;
}

const char* AntiVirus::ScanFile(const char* onefile)
{
	struct cl_scan_options options;
	const char *virname;
    int ret;
    printf("Scan a file: %s\n", onefile);
	if ((ret = cl_scanfile(onefile, &virname, NULL, engine, &options)) == CL_VIRUS) {
		printf("Detected %s virus.\n", virname);
	} else {
		printf("No virus detected.\n");
        virname = NULL;
		if (ret != CL_CLEAN)
			printf("Error: %s\n", cl_strerror(ret));
	}
    return virname;
}

/*static */AntiVirus* AntiVirus::GetInstance()
{
    if (sm_inst == NULL)
    {
        sm_inst = new AntiVirus();
    }
    return sm_inst;
}

void AntiVirus::FreeMemory()
{
	cl_engine_free(engine);
}
